#!/usr/bin/env python
# coding=utf-8

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import logging
import json

class AlidayuAPI(object):
    """docstring for AlidayuAPI"""
    APP_KEY_FIELD = 'KEY_ID'
    APP_SECRET_FIELD = 'ACCESS_SECRET'
    SMS_SIGN_NAME_FIELD = 'SMS_SIGN_NAME_FIELD'
    SMS_TEMPLATE_CODE_FIELD = 'SMS_TEMPLATE_CODE_FIELD'

    def __init__(self, app=None):
        self.url = 'http://gw.api.tbsandbox.com/router/rest'
        self.headers = {
            'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
            "Cache-Control": "no-cache",
            "Connection": "Keep-Alive",
        }
        if app:
            self.init_app(app)

    def init_app(self, app):
        config = app.config
        # print(config)
        # print(config["DEBUG"])
        try:
            self.key = config[self.APP_KEY_FIELD]
            self.secret = config[self.APP_SECRET_FIELD]
            self.sign_name = config[self.SMS_SIGN_NAME_FIELD]
            self.Template_Code = config[self.SMS_TEMPLATE_CODE_FIELD]
            self.api_param = {}


        except Exception as e:
            logging.error(e.args)
            raise ValueError('请填写正确的阿里大鱼配置！')

    def send_sms(self, telephone, code):

        client = AcsClient(self.key, self.secret, 'cn-hangzhou')

        # api_param["code"] = params.get("code")
        request = CommonRequest()
        request.set_accept_format('json')
        request.set_domain('dysmsapi.aliyuncs.com')
        request.set_method('POST')
        request.set_protocol_type('https')  # https | http
        request.set_version('2017-05-25')
        request.set_action_name('SendSms')

        request.add_query_param('RegionId', "cn-hangzhou")
        request.add_query_param('PhoneNumbers', telephone)
        request.add_query_param('SignName', "python论坛")
        request.add_query_param('TemplateCode', self.Template_Code)
        request.add_query_param('TemplateParam', {"code": code})

        response = client.do_action(request)
        # python2:  print(response)
        # print(str(response, encoding='utf-8'))
        result = json.loads(str(response, encoding='utf-8'))

        if result["Code"] == "OK":
            return True
        else:
            print('=' * 10)
            print("阿里大鱼错误信息：", result)
            print('=' * 10)
            return False